import React, { useState, useEffect } from "react";
import { Link, withRouter } from "react-router-dom";
import { Layout, Menu } from "antd";
import menuList from "@/config/menuConfig";
const { SubMenu } = Menu;
const { Sider } = Layout;

function LeftNav(props) {
  const [openKey, setOpenKey] = useState('')
  const [menuNodes, setMenuNodes] = useState('')
  // 递归生成菜单
  const getMenuList = menuList => {
    const path = props.location.pathname
    return menuList.map(item => {
      if (!item.children) {
        return (
          <Menu.Item key={item.key} icon={item.icon}>
            <Link to={item.key}>{item.title}</Link>
          </Menu.Item>
        );
      } else {
        const isPath = item.children.find(cItem => cItem.key === path);
        if (isPath) {
          setOpenKey(item.key)
        }

        return (
          <SubMenu key={item.key} icon={item.icon} title={item.title}>
            {getMenuList(item.children)}
          </SubMenu>
        );
      }
    });
  };

  useEffect(() => {
    const temp = getMenuList(menuList)
    setMenuNodes(temp)
  }, [])

  let path = props.location.pathname
  return (
    <Sider width={200} className='site-layout-background'>
      <Menu
        mode='inline'
        selectedKeys={[path]}
        openKeys={[openKey]}
        style={{ height: "100%", borderRight: 0 }}
      >
        { menuNodes }
      </Menu>
    </Sider>
  );
}
/*
withRouter 高阶组件
包装非路由组件，返回一个新的组件
新的组件向非路由组件传递3个属性： history location match
*/
export default withRouter(LeftNav);
